package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-04-12
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try{
            InputStream in = file.getInputStream();

            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //课程列表---》树形
    @Override
    public List<OneSubject> getALLSubject() {
        //  1. 查询所有的一级分类
        QueryWrapper<EduSubject> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("parent_id","0");
        //  this.list(wrapper1) 同样可以实现查询效果
        List<EduSubject> onesubjects = baseMapper.selectList(wrapper1);

        //  2. 查询所有二级分类
        QueryWrapper<EduSubject> wrapper2 = new QueryWrapper<>();
        wrapper1.ne("parent_id","0");
        List<EduSubject> twosubjects = baseMapper.selectList(wrapper2);

        //创建list集合，存储最终封装的数据
        List<OneSubject> finalList = new ArrayList<>();

        //  3. 封装一级分类   遍历onesubjects
        for (EduSubject one:onesubjects){
            OneSubject o = new OneSubject();
            BeanUtils.copyProperties(one,o);
//            o.setId(one.getId());
//            o.setTitle(one.getTitle());

            List<TwoSubject> twoList = new ArrayList<>();
            //  4. 封装二级分类
            for (EduSubject two:twosubjects) {
                if(two.getParentId().equals(one.getId())){
                    TwoSubject t = new TwoSubject();
                    BeanUtils.copyProperties(two,t);
                    twoList.add(t);
                }
            }
            //把二级分类放入一级分类
            o.setChildren(twoList);
            //把一级分类放入finalList
            finalList.add(o);
        }
        return finalList;
    }
}
